package raft

import (
	"sync"
	"time"
)

type Timer struct {
	timer  *time.Timer
	waitMs int
	mu     sync.Mutex
}

func makeTimer() *Timer {
	timer := &Timer{}
	timer.timer = time.NewTimer(10000 * time.Second)
	timer.timer.Stop()
	return timer
}
func (timer *Timer) stop() {
	timer.mu.Lock()
	defer timer.mu.Unlock()
	if !timer.timer.Stop() {
		select {
		case <-timer.timer.C:
		default:
		}
	}
}

func (timer *Timer) setWaitMs(waitMs int) {
	timer.mu.Lock()
	timer.waitMs = waitMs
	timer.mu.Unlock()
}

func (timer *Timer) start() {
	timer.stop()
	timer.mu.Lock()
	duration := time.Duration(timer.waitMs) * time.Millisecond
	defer timer.mu.Unlock()
	timer.timer.Reset(duration)
	<-timer.timer.C
}
